import User from '../data/model/User.js';

async function fnGUsers(ctx, next) {
  let res = `not object`;

  let users = await User.findAll();

  if (users) {
    res = {
      code: 200,
      message: "获取用户成功",
      data: user,
    };
  } else {
    res = {
      code: 500,
      message: "失败",
      data: null,
    };
  }
  ctx.body = res;

}

async function fnGUser(ctx, next) {
  let res = `not object`;

  const id = ctx.params.id || 0;
  const user = await User.findByPk(id);

  if (user) {
    res = {
      code: 200,
      message: "查询成功",
      data: user,
    };
  } else {
    res = {
      code: 500,
      message: "用户不存在",
      data: null,
    };
  }

  ctx.status = 200;
  ctx.body = res;
}

async function fnPOUser(ctx, next) {
  let res = `not object`;

  const obj = ctx.request.body;
  
  console.log(obj);

  const Pass = await User.create(obj);

  if (Pass) {
    res = {
      code: 200,
      message: "新增成功",
      data: null,
    };
  } else {
    res = {
      code: 500,
      message: "新增失败",
      data: null,
    };
  }

  ctx.status = 200;
  ctx.body = res;
}
async function fnPUUser(ctx, next) {
  let res = `not object`;

  const id = ctx.params.id || 0;
  const obj = ctx.request.body;

  const Pass = await User.findByPk(id);

  if (Pass) {
    const updatePass = await User.update(obj, { where: { id } });
    if (updatePass) {
      res = {
        code: 200,
        message: "修改成功",
        data: null,
      };
    } else {
      res = {
        code: 500,
        message: "修改失败",
        data: null,
      };
    }
  } else {
    res = {
      code: 500,
      message: "用户不存在,修改失败",
      data: null,
    };
  }

  ctx.status = 200;
  ctx.body = res;
}
async function fnDUser(ctx, next) {
  let res = `not object`;

  const id = ctx.params.id || 0;
  const user = await User.findByPk(id);

  if (user) {
    const Pass = await User.destroy({ where: { id } });

    if (Pass) {
      res = {
        code: 200,
        message: "删除成功",
        data: null,
      };
    } else {
      res = {
        code: 500,
        message: "删除失败",
        data: null,
      };
    }
  } else {
    res = {
      code: 500,
      message: "用户不存在",
      data: null,
    };
  }

  ctx.status = 200;
  ctx.body = res;
}

export const object = [
  // allUser
  {
    method: "get",
    url: "/Users",
    function: fnGUsers()
  },
  // oneUser
  {
    method: "get",
    url: "/Uesr",
    function: fnGUser()
  },
  // addUser
  {
    method: "post",
    url: "/Uesr",
    function: fnPOUser()
  },
  //editUser
  {
    method: "put",
    url: "/Uesr/:id",
    function: fnPUUser()
  },
  //delUser
  {
    method: "delete",
    url: "/Uesr/:id",
    function: fnDUser()
  }
]